package org.mosquitos.chat;

import java.util.Enumeration;
import java.util.Map;

import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.endpoint.EndpointAddress;
import net.jxta.protocol.DiscoveryResponseMsg;
import net.jxta.protocol.PeerAdvertisement;

public class PeerAdvertisementListener implements DiscoveryListener {
	private Map<String,Object> userList;

	public PeerAdvertisementListener(Map<String,Object> userList){
		this.userList = userList;
	}

	public void discoveryEvent(DiscoveryEvent de) {
        EndpointAddress ea = (EndpointAddress)de.getSource();
        
        DiscoveryResponseMsg res = de.getResponse();
        Enumeration<?> enum_ = res.getAdvertisements();
        
        PeerAdvertisement pa = null;
        boolean addNew = false;
		if (enum_ != null) {
			while (enum_.hasMoreElements()) {
				pa = (PeerAdvertisement)enum_.nextElement();
				
				//&& ea.getProtocolAddress().equals(pa.getPeerID().getUniqueValue())
		        if(!userList.containsKey(pa.getName()) ){
		        	userList.put(pa.getName(), pa);
		        	addNew = true;
		        	System.out.println("add peer:"+pa.getName());
		        	//System.out.println("pa:"+pa);
		        }else{
		        	//System.out.println("peer :"+pa.getName()+" has been exist");
		        }
			}
		}

        if(addNew){
        	showUserList(userList);
        }
	}

	private void showUserList(Map<String,?> userList){
		
	}
}
